<template>
  <div class="auth-container">
    <div class="background-image"></div>
    <div class="header-bar">
      <span class="header-title">开放街景平台</span>
    </div>
    <div class="overlay">
      <el-card class="auth-card">
        <div class="header">
          <h2>用户注册</h2>
        </div>
        <el-form
            :model="form"
            ref="registerForm"
            :rules="rules"
            label-position="top"
            @submit.prevent="handleRegister"
        >
          <el-form-item label="注册类型" prop="userType">
            <el-radio-group v-model="form.userType" @change="handleUserTypeChange">
              <el-radio label="public">普通用户</el-radio>
              <el-radio label="admin">管理员</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="form.username" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="form.confirmPassword" type="password" placeholder="请再次输入密码" show-password />
          </el-form-item>
          <el-form-item v-if="form.userType === 'admin'" label="管理员密钥" prop="adminKey">
            <el-input v-model="form.adminKey" type="password" placeholder="请输入管理员密钥" show-password />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" native-type="submit" :loading="loading" size="large" style="width: 100%">
              注册
            </el-button>
          </el-form-item>
          <div class="footer">
            <router-link to="/login" class="auth-link">已有账号？立即登录</router-link>
          </div>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { defineComponent } from 'vue'
import { ElMessage } from 'element-plus'

export default defineComponent({
  props: {
    loading: {
      type: Boolean,
      default: false,
    },
  },
  emits: ['register-success'],
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value !== this.form.password) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    };
    const validateAdminKey = (rule, value, callback) => {
      if (this.form.userType === 'admin' && !value) {
        callback(new Error('请输入管理员密钥'));
      } else if (this.form.userType === 'admin') {
        this.$api.validateAdminKey(value).then(response => {
          if (response.data.code !== "200") {
            callback(new Error('管理员密钥不正确'));
          } else {
            callback();
          }
        }).catch(() => {
          callback(new Error('密钥验证失败'));
        });
      } else {
        callback();
      }
    };
    return {
      form: {
        userType: 'public',
        username: '',
        password: '',
        confirmPassword: '',
        adminKey: '',
      },
      rules: {
        userType: [{ required: true, message: '请选择注册类型', trigger: 'change' }],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 4, max: 16, message: '长度在4到16个字符', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在6到20个字符', trigger: 'blur' },
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validatePassword, trigger: 'blur' },
        ],
        adminKey: [{ validator: validateAdminKey, trigger: 'blur' }],
      },
    };
  },
  methods: {
    handleUserTypeChange() {
      this.$refs.registerForm.clearValidate('adminKey');
    },
    async handleRegister() {
      this.$refs.registerForm.validate(async (valid) => {
        if (!valid) return;
        try {
          const response = await this.$api.register({
            username: this.form.username,
            password: this.form.password,
            permission: this.form.userType === 'admin' ? 1 : 0,
            adminKey: this.form.userType === 'admin' ? this.form.adminKey : '',
          });
          if (response.data.code === "200" || response.data.code === "0") {
            const userData = response.data.data;
            const user = userData || {};
            const permission = user.permission || (this.form.userType === 'admin' ? 1 : 0);

            localStorage.setItem('user', JSON.stringify(user));
            localStorage.setItem('permission', permission);

            ElMessage.success('注册成功');
            this.$router.push('/login');
          } else {
            ElMessage.error(response.data.message || '注册失败');
          }
        } catch (error) {
          ElMessage.error('注册请求失败: ' + (error.message || '未知错误'));
          console.error('Register error:', error);
        }
      });
    }
  },
});
</script>

<style scoped>
/* 使用与登录页面相同的样式 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html, body {
  height: 100%;
  overflow: hidden;
}

.auth-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}

.background-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('../assets/background-3.jpg');
  background-size: cover;
  background-position: center;
  z-index: 0;
}

.header-bar {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 60px;
  background-color: rgba(0, 128, 113, 0.7);
  display: flex;
  align-items: center;
  padding-left: 30px;
  z-index: 2;
  color: white;
  font-size: 20px;
  font-weight: 500;
}

.overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding-top: 60px;
}

.auth-card {
  width: 420px;
  padding: 30px;
  border-radius: 16px;
  background-color: rgba(255, 255, 255, 0.95);
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.2);
}

.header {
  text-align: center;
  margin-bottom: 25px;
}

.header h2 {
  font-weight: 600;
  font-size: 26px;
  color: #333;
}

.footer {
  text-align: center;
  margin-top: 15px;
}

.auth-link {
  color: #409eff;
  font-size: 14px;
  text-decoration: none;
}

.auth-link:hover {
  text-decoration: underline;
}
</style>
